/**
 * Copyright 2017 Alibaba.com All right reserved. This software is the
 * confidential and proprietary information of Alibaba.com ("Confidential
 * Information"). You shall not disclose such Confidential Information and shall
 * use it only in accordance with the terms of the license agreement you entered
 * into with Alibaba.com.
 * <p>
 * File generated at: 2017年7月19日下午9:09:53
 */
package com.aliyun.messagemgt.common.exceptions;


import com.aliyun.messagemgt.common.errorcode.IErrorCode;
import org.apache.commons.lang3.ArrayUtils;
import org.apache.commons.lang3.StringUtils;

/**
 * 主动抛异常时，应使用此异常类
 *
 * @author 晨泽
 * @created 2017/12/18
 * @version people-archive 1.0
 */
public class BaseException extends RuntimeException {

    private static final long serialVersionUID = -6998264217029924353L;

    private IErrorCode errorCode;

    public BaseException(IErrorCode errorCode, Object... vars) {
        super(buildErrMsg(errorCode, vars));
        this.errorCode = errorCode;
    }

    public BaseException(IErrorCode errorCode, Throwable cause, Object... vars) {
        super(buildErrMsg(errorCode, vars), cause);
        this.errorCode = errorCode;
    }

    /**
     * 构造错误消息
     *
     * @param    errorCode        错误码实现类
     * @param    vars            变量
     * @return String            错误消息
     * @author 马军(瀚尘)
     * @created 2017年7月20日上午10:35:31
     * @version 2.0
     */
    private static String buildErrMsg(IErrorCode errorCode, Object... vars) {
        String errMsgTemplate = errorCode.errMsgTemplate();
        if (StringUtils.isBlank(errMsgTemplate)) {
            return errorCode.errName();
        }
        if (ArrayUtils.isEmpty(vars)) {
            return errMsgTemplate;
        }
        return String.format(errMsgTemplate.replaceAll("\\{\\w*\\}", "%s"), vars);
    }

    public IErrorCode getErrorCode() {
        return errorCode;
    }

}
